package com.ymt.bpm.appboot;

import com.ymt.bpm.engine.listener.EventRegister;
import org.activiti.engine.RuntimeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Set;

/**
 * Created by Johnny on 2016/12/23.
 * This class is for initialize the bpm engine, do some initial actions such as
 * adding activiti listeners.
 */
@Component
public class EngineInitializer {

    /**
     * Logger
     */
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Activiti RuntimeService bean
     */
    @Autowired
    private RuntimeService runtimeService;
    /**
     * CommonEventListener for engine events
     */
    @Autowired
    private EventRegister eventRegister;

    /**
     * init the engine
     */
    public void init() {
        logger.info("init...");

        //register event listeners
        logger.info("Registering event listeners...");
        eventRegister.registerEvents();

        logger.info("init done.");
    }

    public void refresh() {
        logger.info("refresh...");
    }

    public void stop() {
        logger.info("stop...");

        logger.info("Deregistering jdbc driver.");
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            try {
                DriverManager.deregisterDriver(driver);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        logger.info("Closing all database connections.");
        destroyThreads();
        logger.info("All db threads stopped.");
    }

    private void destroyThreads(){
        final Set<Thread> threads = Thread.getAllStackTraces().keySet();
        for (Thread thread : threads) {
            if(thread.getName().equals("HouseKeeper")){
                synchronized (this) {
                    try {
                        thread.stop();
                        return;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
